package com.york.tinyrpc.protoss.bootstrap;

import com.york.tinyrpc.protoss.TinyRpcApplication;
import com.york.tinyrpc.protoss.config.RegistryCenterConfig;
import com.york.tinyrpc.protoss.config.TinyRpcConfig;
import com.york.tinyrpc.protoss.model.ServiceMetaInfo;
import com.york.tinyrpc.protoss.model.ServiceRegistryInfo;
import com.york.tinyrpc.protoss.registry.LocalRegistry;
import com.york.tinyrpc.protoss.registry.center.RegistryCenter;
import com.york.tinyrpc.protoss.registry.center.RegistryCenterFactory;
import com.york.tinyrpc.protoss.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 提供方启动类
 */
public class TinyRpcProviderBootstrap {

    /**
     * 初始化
     */
    public static void init(List<ServiceRegistryInfo<?>> serviceRegistryInfos) {
        // RPC 框架初始化（配置和注册中心）
        TinyRpcApplication.init();
        // 全局配置
        final TinyRpcConfig rpcConfig = TinyRpcApplication.getRpcConfig();

        // 注册服务
        for (ServiceRegistryInfo<?> serviceRegisterInfo : serviceRegistryInfos) {
            String serviceName = serviceRegisterInfo.getServiceName();
            // 本地注册
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            // 注册服务到注册中心
            RegistryCenterConfig registryCenterConfig = rpcConfig.getRegistryCenterConfig();
            RegistryCenter registryCenter = RegistryCenterFactory.getRegistryCenterByType(registryCenterConfig.getRegistryCenterType());
            ServiceMetaInfo serviceMetaInfo = ServiceMetaInfo.builder()
                    .serviceName(serviceName)
                    .serviceHost(rpcConfig.getServerHost())
                    .servicePort(rpcConfig.getServerPort())
                    .serviceVersion(rpcConfig.getVersion())
                    .build();

            try {
                registryCenter.serviceRegister(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + " 服务注册失败", e);
            }
        }

        // 启动服务器
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(rpcConfig.getServerPort());
    }

}
